#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <sys/types.h>
#include <string.h>
#include <assert.h>
#include <sys/stat.h>
#include <fcntl.h>
#define MAX 1024
#define ARG 64
#define FREE " "
enum redir{
  REDIR_INPUT=0,
  REDIR_OUTPUT,
  REDIR_APPEND,
  REDIR_NONE
};

char* checkDir(char commandstr[],enum redir* redir_type)
{
  while(*commandstr)
  {
   if(*commandstr=='>')
   {

    if(*(commandstr+1)=='>')
    {
     *redir_type=REDIR_APPEND;
     *(commandstr)='\0';
     return commandstr+2;
    }
    *redir_type=REDIR_OUTPUT;
    *(commandstr)='\0';
    return commandstr+1;
   }
   if(*commandstr=='<')
   {
     *redir_type=REDIR_INPUT;
    *(commandstr)='\0';
    return commandstr+1;
   }
commandstr++;
  }
  return NULL;
}

int divorce(char* command,char* arr[])
{
  assert(command);
  assert(arr);
  arr[0]=strtok(command,FREE);
  if(arr[0]==NULL)
  {
    return -1;
  }
  int i=1;
while((arr[i++]=strtok(NULL,FREE)));
return 0;
}

void Print(char* arr[])
{
for(int i=0;arr[i];i++)
{
  printf("%d:%s\n",i,arr[i]);
}

}

extern char** environ;
void Showenv()
{
for(int i=0;environ[i];i++)
{
printf("%d:%s\n",i,environ[i]);
}


}





int main()
{
    int last_code=0;
  while(1)
  {
    

    enum redir redir_type=REDIR_NONE;
    char tmp[64][256];
    int env_i=0;
   char command[MAX]={0};
   char* arr[ARG]={NULL};
   printf("[user@robot Current]");
   fflush(stdout);
   fgets(command,sizeof(command),stdin);
   command[strlen(command)-1]='\0';
   char* filename=checkDir(command,&redir_type);
   printf("%s,%d",filename,redir_type);
   //printf("%s",command);
   divorce(command,arr);
   //Print(arr);
  if(strcmp(arr[0],"cd")==0)
  {
    if(arr[1]!=NULL)
    chdir(arr[1]);
  continue;
  }
 if(strcmp(arr[0],"ls")==0)
 {
   int i=0;
  while(arr[i]) i++;
  arr[i]=(char*)"--color=auto";
  arr[++i]=NULL;
 }

 if(strcmp(arr[0],"export")==0)
 {
   if(arr[1]!=NULL)
   {
  strcpy(tmp[env_i],arr[1]);
  putenv(tmp[env_i++]);
   }
   continue;
 }
if(strcmp(arr[0],"env")==0)
{
Showenv();
continue;
}
if(strcmp(arr[0],"echo")==0)
{
if(*arr[1]=='$')
{

if(*(arr[1]+1)=='?')
{
  printf("%d\n",last_code);
}
else
{
printf("%s\n",getenv((arr[1]+1)));

}

}
continue;



}
    int ret=fork();
   assert(ret>=0);
   if(ret==0)
   {
   //子进程
    if(redir_type!=REDIR_NONE)
    {
      printf("已进入\n");
     if(redir_type==REDIR_OUTPUT)
     {
       int fd=open(filename,O_WRONLY|O_CREAT|O_TRUNC,0666);
       dup2(fd,1);
     }
     if(redir_type==REDIR_APPEND)
     {
       int fd=open(filename,O_WRONLY|O_CREAT|O_APPEND,0666);
      dup2(fd,1);
     }
    if(redir_type==REDIR_INPUT)
    {
  int fd=open(filename,O_RDONLY);
  dup2(fd,0);
    }

    }




   execvp(arr[0],arr); 
   exit(-1);
   }
   int status=0;
 int  waitret =waitpid(ret,&status,0); 
 if(waitret>0)
   last_code=(status>>8)&0xFF;

  }

  return 0;
}
